package com.yxplearn.mybatisplus.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.lucene.util.RamUsageEstimator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class CacheController {

    private Map<Long, User> userCache = new HashMap<>();

    @RequestMapping("/buildCache")
    @ResponseBody
    public String buildCache() {
        for (int i = 0; i < 10000; i++) {
            User user = new User(IdWorker.getId(), "yxp", "address", i);
            userCache.put(user.getId(), user);
        }
        return "ok";
    }

    @RequestMapping("/removeCache")
    @ResponseBody
    public String removeCache() {
        userCache.clear();
        return "ok";
    }

    @RequestMapping("/cmpCache")
    @ResponseBody
    public String cmpCache() {
        User user = new User(IdWorker.getId(), "yxp", "address", 5);
        int mb = getMb(user);
        System.out.println(mb);
        return "ok";
    }

    private int getMb(Object obj) {

        if (obj == null) {
            return 0;
        }
        //计算指定对象本身在堆空间的大小，单位字节
        long byteCount = RamUsageEstimator.shallowSizeOf(obj);
        if (byteCount == 0) {
            return 0;
        }
        double oneMb = 1 * 1024 * 1024;

        if (byteCount < oneMb) {
            return 1;
        }

        Double v = Double.valueOf(byteCount) / oneMb;
        return v.intValue();
    }


    @Data
    @AllArgsConstructor
    private static class User {
        private long id;// 8 byte
        private String name;//4 byte
        private String address;//4 byte
        private int age;// 4 byte
    }
}
